// Copyright 2018 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.


// There's a typo in the line below; oninstalled should be onInstalled.
chrome.runtime.onInstalled.addListener(function() {
    
  chrome.storage.sync.set({vip_paser_url: 'https://github.rc1844.workers.dev'}, function() {
  });

  
//   chrome.commands.onCommand.addListener(function(command) {
    
//   });
});

function genericOnClick(info, tab) {
    console.log("item " + info.menuItemId + " was clicked");
    console.log("info: " + JSON.stringify(info));
    console.log("tab: " + JSON.stringify(tab));
  }
  

chrome.contextMenus.create({
    "title": "github加速打开",
    "contexts": ["page"],
    "onclick":function(info, tab){
        genericOnClick(info,tab);
        chrome.storage.sync.get(['vip_paser_url'], function(result) {
            if (tab.url.indexOf('https://github.com') === -1) {
                alert('当前页面url非github.com官方地址，暂不支持替换');
                return;
            }
            chrome.tabs.remove(tab.id);
            //  console.log('Value currently is ' + JSON.stringify(result));
            let uri = tab.url.substr(18);
            window.open(result.vip_paser_url+uri);
            
            // chrome.tabs.executeScript(tab.id,{
            //     code:"<script>window.location.href='"+result.vip_paser_url+tab.url+"</script>"
            // },function(result){
                
            // });
        });
        
    }
});

chrome.contextMenus.create({
    "title": "连接github加速",
    "contexts": ["link"],
    "onclick":function(info, tab){
        // genericOnClick(info,tab);
        chrome.storage.sync.get(['vip_paser_url'], function(result) {
            // console.log('Value currently is ' + JSON.stringify(result));
            if (info.linkUrl.indexOf('https://github.com') === -1) {
                alert('选中的url非github.com官方地址，暂不支持替换');
                return;
            }
            let uri = info.linkUrl.substr(18);
            window.open(result.vip_paser_url+uri);
        });
        
        
    }
});
chrome.contextMenus.create({
    'title': "使用github加速",
    "contexts": ['selection'],
    "onclick": function(info, tab){
        chrome.storage.sync.get(['vip_paser_url'], function(result) {
            // console.log('Value currently is ' + JSON.stringify(result));
            if (info.selectionText.indexOf('https://github.com') === -1) {
                alert('选中的url非github.com官方地址，暂不支持替换');
                return;
            }
            let uri = info.selectionText.substr(18);
            window.open(result.vip_paser_url+uri);
        });
    }
})
